import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';
import eslintPlugin from 'vite-plugin-eslint';
import AutoImport from 'unplugin-auto-import/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import IconsResolver from 'unplugin-icons/resolver';
import compression from 'vite-plugin-compression';
import { createHtmlPlugin } from 'vite-plugin-html';
import * as path from 'path';
// https://vitejs.dev/config/
export default defineConfig(({ mode }) => {
  const root = process.cwd();
  const env = loadEnv(mode, root);
  return {
    base: './',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src')
      }
    },
    plugins: [
      vue(),
      eslintPlugin(), // esLint 报错信息显示在浏览器界面上
      compression({
        ext: '.gz',
        deleteOriginFile: false
      }), //打包gzip压缩
      createHtmlPlugin({
        minify: true,
        inject: {
          data: { title: env.VITE_GLOB_APP_TITLE }
        }
      }),
      AutoImport({
        imports: ['vue', 'vue-router', '@vueuse/core', 'pinia', 'vue-i18n'],
        resolvers: [
          // 自动导入 Element Plus 相关函数ElMessage, ElMessageBox... (带样式)
          ElementPlusResolver(),
          IconsResolver({
            prefix: 'Icon'
          })
        ],
        dts: 'src/auto-imports.d.ts'
      }) // 自动导入
    ],
    server: {
      host: '0.0.0.0',
      port: 60003,
      open: false,
      proxy: {
        '/api': {
          target: 'http://192.168.31.200:7000',
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, '')
        }
      }
    },
    build: {
      outDir: 'dist',
      assetsDir: 'assets', //指定静态资源存放路径
      sourcemap: false, //是否构建source map 文件
      // esbuild 打包更快，但是不能去除 console.log，terser打包慢，但能去除 console.log
      minify: 'terser', // 混淆器，terser 构建后文件体积更小，'terser' | 'esbuild'
      chunkSizeWarningLimit: 3800, //chunk 大小警告的限制，默认500KB
      reportCompressedSize: false, // 禁用 gzip 压缩大小报告，可略微减少打包时间
      rollupOptions: {
        output: {
          // 最小化拆分包
          manualChunks(id) {
            if (id.includes('node_modules')) {
              return id.toString().split('node_modules/')[1].split('/')[0].toString();
            }
          },
          chunkFileNames: 'assets/js/[name]-[hash].js',
          entryFileNames: 'assets/js/[name]-[hash].js',
          assetFileNames: 'assets/[ext]/[name]-[hash].[ext]'
        }
      },
      terserOptions: {
        // 生产环境移除console
        compress: {
          drop_console: false,
          drop_debugger: true
        },
        // 10月更新
        output: {
          comments: true // 去掉注释内容
        }
      }
    }
  };
});
